<template>
  <div id="allDiv">
    <headBu />
    <hr />
    <div id="userIfon">
      <div id="touxiang">
        <img :src=imageUrl alt="">
        <el-button type="success" size="small" id="xiugai">修改</el-button>
        <div id="input1"><input type="file" accept="image/*" aria-label="选择头像" @change="uploadFile" /></div>
      </div>
      <div id="info">
        <div id="userName">{{ usersName }}</div>
        <div id="jingdu">
          <div>
            <div class="zhi">{{ oldTime }}</div>
            <div>学习天数</div>
          </div>
          <div>
            <div class="zhi">{{ this.$store.state.knowlegeCount}}/36</div>
            <div>知识点</div>
          </div>
          <div>
            <div class="zhi">{{ this.$store.state.AchievementValue}}</div>
            <div>成就值</div>
          </div>

        </div>
      </div>
    </div>
    <div id="share">
      <div id="share1">
        <div class="P1">玩中学习，乐享数学!</div>
        <div class="P2">小学数学APP，让孩子爱上学习！！</div>
      </div>
      <div @click="shareTo"> <el-button type="success" style="padding: 10px;margin-left: -15vw;"
          size="mini">点击分享</el-button></div>
    </div>
    <div id="fenxi">
      <li @click="checkIn"><i class="el-icon-date">今日打卡</i><i class="el-icon-arrow-right" style=""></i></li>
      <li @click="dialogFormVisible = true"><i class="el-icon-edit-outline">编辑资料</i><i class="el-icon-arrow-right"
          style=""></i></li>
      <li><i class="el-icon-message" @click="showModal = true">联系客服</i><i class="el-icon-arrow-right" style=""></i></li>
      <li><i class="el-icon-user">退出登录</i></li>
      <!-- <div id="main2" style="width:94.5vw;height:40vh;margin-top: 5vh;"></div>
      <div id="main" style="width:94.5vw;height:40vh;"></div> -->
    </div>
    <ShareCode :isAlert="isAlert" :url="href" @alertBack="alertBackFn"></ShareCode>
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <button @click="showModal = false" class="close-btn">&times;</button>
        <div>
          <p>请扫描二维码，联系客服</p>
          <img src="https://wincan.oss-cn-chengdu.aliyuncs.com/qrcode_for_gh_a47860c9e902_344.jpg" alt="">
        </div>
      </div>
    </div>
    <el-dialog title="重置密码" :visible.sync="dialogFormVisible" width="90%">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" class="phone-input"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <br>
        <div class="input-group" style="display:flex">
        <el-input v-model="form.code" style="margin-left:-5px"></el-input>
        <div style="width:10px"></div>
        <el-button @click="handleGetCode" :disabled="countdown > 0" class="code-button" style="padding:5px">
            {{ countdown > 0 ? `${countdown}s 后重试` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="form.confirmPassword"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false" size="small">取消</el-button>
      <el-button type="primary" @click="handleSubmit" size="small">提交</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import OSS from 'ali-oss';
import HeadBu from "@/components/Head/head2.vue";
import { getUser, modifedPicture } from "@/api/users"
import EditorInfo from '@/components/EditorInfo/EditorInfo.vue';
import ShareCode from "./ShareCode.vue"
import {modifedPasswrold} from "@/api/users"
export default {
  components: { HeadBu, EditorInfo, ShareCode },
  data() {
    return {
      findObj: {},
      oldTime: 0,
      konwLegeCount:0,
      imageUrl: " https://wincan.oss-cn-chengdu.aliyuncs.com/adult-g3a772ea94_1280.jpg",
      isAlert: false,
      showModal: false,
      dialogFormVisible: false,
      usersName:"用户1",
      form: {
        phone: '',
        code: '',
        password: '',
        confirmPassword: ''
      },
      countdown: 0,
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{8,16}$/, message: '密码必须包含大小写字母和数字，长度为8-16位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    getUser().then(
      res => {
        var contenTest = this
        Array.from(res).forEach(item => {
          if (sessionStorage.userName == item.userName) {
            const now = new Date();
            const timeDiff = now.getTime() - item.dateTime;
            contenTest.imageUrl = item.headPicture
            contenTest.usersName = item.userName
          }
        })
      }
    ).catch(
      error => {
        console.log(error)
      }
    )
  },
  mounted() {
  },
  methods: {
    async uploadFile(event) {
      const contentText = this
      const file = event.target.files[0];
      const client = new OSS({
        region: 'oss-cn-chengdu',
        secure: true,
        accessKeyId: 'LTAI5tKbhZ32WKmMX8BAnKDw',
        accessKeySecret: 'fYQSEdyVwWyEzldKLao0wGoiugDi1T',
        bucket: 'wincan'
      });
      try {
        const result = await client.put(file.name, file);
        const imageUrl = result.url;
        console.log('upload success:', imageUrl);
        this.imageUrl = imageUrl;
        getUser().then(//获取目前ID
          res => {
            const nowUser = Array.from(res).filter(item => {
              return item.userName == sessionStorage.getItem("userName")
            })
            console.log(nowUser)
            contentText.findObj["id"] = nowUser[0].id
            contentText.findObj["userName"] = sessionStorage.getItem("userName")
            contentText.findObj["dataTime"] = this.oldTime
            contentText.findObj["headPicture"] = this.imageUrl
          }
        ).then(() => {
          modifedPicture(this.findObj).then(res => {
            this.$message({
              message: '头像修改成功',
              type: 'success'
            });
            console.log(res)
          }).catch(error => {
            console.log(error)
          }
          )
        }).catch(
          error => {
            console.log(error)
          }
        )
      } catch (e) {
        console.log('upload failed:', e);
      }
    },
    shareTo() {
      this.isAlert = true;
    },
    alertBackFn() {
      this.isAlert = false
    },
    checkIn() {
      // 获取当前日期
      const now = new Date().toLocaleDateString();
      // 从本地存储中获取打卡记录
      const checkInRecord = sessionStorage.getItem("checkInRecord") || "{}";
      const checkInRecordObj = JSON.parse(checkInRecord);
      // 检查是否已经打卡
      if (checkInRecordObj[now]) {
        this.$message.error('今日已经打过卡了');
        return;
      }
      this.oldTime++
      // 更新打卡记录
      checkInRecordObj[now] = true;
      sessionStorage.setItem("checkInRecord", JSON.stringify(checkInRecordObj));
      this.$message({
        message: '打卡成功',
        type: 'success'
      });
    },
    handleGetCode() {
      // 在这里发送获取验证码的请求
      // 如果请求成功，设置倒计时
      this.sendCode()
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown === 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    }, 
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 在这里发送重置密码的请求，传递手机号、验证码和新密码
          // 如果请求成功，关闭对话框
          const data = {
            phone: this.form.phone,
            code: this.form.code,
            password: this.form.password
          };
          this.verifyCode()
        } else {
          return false;
        }
      });
    },
    sendCode() {
      // 发送短信验证码
      fetch('http://localhost:3001/api/sendCode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone: this.form.phone }),
      })
        .then(res => res.json())
        .then(data => {
          if (data.code==0) {
            this.$message.success('验证码发送成功！');
          } else {
            this.$message.error('验证码请求失败！');
          }
        })
        .catch(err => {
          console.error(err)
          this.message = '验证码发送失败'
        })
    },
    verifyCode() {
      // 验证短信验证码
      fetch('http://localhost:3001/api/verifyCode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json', 
        },
        body: JSON.stringify({ phone: this.form.phone, code: this.form.code }),
      })
        .then(res => res.json())
        .then(data => {
          if (data.code==0) {
            modifedPasswrold(this.form.password,sessionStorage.getItem("isWho")).then(
              ()=>{
                this.$message.success('密码修改成功！');
              }
            )
            this.dialogFormVisible = false;
          } else {
            this.$message.error('验证码错误！');
          }
        })
        .catch(err => {
          console.error(err)
          this.message = '验证码验证失败'
        })
    },
  },
  computed: {
    statyDay() {
    },
    href() {
      if (typeof window !== 'undefined') {
        return window.location.href
      }
    }
  },
};
</script>

<style lang="less" scoped>
.el-dialog__wrapper {
  /* 控制垂直居中 */
  display: flex;
  justify-content: center;
  align-items: center;
}
 .my-dialog .el-dialog__body {
    display: flex;
    justify-content: center;
    align-items: center;
  }

/* 手机号码输入框样式 */
.phone-input {
  flex: 1;
}

/* 验证码按钮样式 */
.code-button {
  margin-left: 10px;
}

/* 在小屏幕上，将手机号码输入框和验证码按钮放在同一行 */
@media (max-width: 480px) {
  .phone-input {
    margin-right: 10px;
  }
  .code-button {
    margin-left: 0;
  }
} 
.modal {
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  position: relative;

  img {
    object-fit: contain;
    width: 80vw;
    height: 80vw;
  }
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 1.5rem;
  background-color: transparent;
  border: none;
  cursor: pointer;
  outline: none;
}

#xiugai {
  // margin-top: 7vh;
  margin-top: -2vw;
  transform: scale(0.75);
}

#input1 {
  border: 1px solid white;
  ;
  margin-top: -4vh;
  position: absolute;
  opacity: 0;
}

.P1 {
  border: 1p solid white;
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
  letter-spacing: 2px;
  margin-bottom: 1vh;
}

.P2 {
  font-size: 15px;
  color: rgb(237, 237, 237);
}

#share {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: rgb(229, 65, 65);
  width: 92vw;
  height: 10vh;
  margin: 2vh auto;
  border-radius: 5px;
  text-align: left;
  text-indent: 5px;

  #share1 {
    width: 80vw;
    height: 10vh;
  }
}

#userIfon {
  border-radius: 5px;
  height: 17vh;
  width: 95vw;
  background-color: rgb(255, 255, 255);
  display: flex;
  justify-content: space-around;
  align-items: center;

  #userName {
    margin-top: 1vh;
    font-size: 20px;
    text-align: left;
    letter-spacing: 2px;
    font-weight: 600;
    text-indent: 10px;
  }

  #touxiang {
    width: 18vw;
    background-color: rgb(228, 220, 220);
    border-radius: 50%;
    height: 18vw;
    margin-top: -3vh;

    img {
      width: 18vw;
      height: 18vw;
      object-fit: cover;
      border-radius: 50%;
    }
  }
}

#allDiv {
  height: 100vh;
}

#main {
  font-size: 12px;
  letter-spacing: 0;
}

#main2 {
  margin: 20px 0 20px 0;
}

#fenxi {
  // height: 400px;
  padding: 2vw;
  border: 2vw solid white;
  height: 50vh;
  background-color: rgb(245, 244, 244);
  margin-top: 20px;
  letter-spacing: 2px;
  font-weight: bold;
  margin-bottom: 100px;
  border-radius: 5px 5px 0 0;
  text-align: left;
  width: 85vw;
  margin: 0 auto;

  i {
    padding-right: 5px;
    font-weight: 540;
  }

  li {
    font-family: 'Courier New', Courier, monospace;
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-indent: 4px;
    list-style: none;
    height: 6vh;
    line-height: 5vh;
    font-size: 17px;
    border-bottom: 1px solid rgb(171, 170, 170);
  }

  li:hover {
    color: white;
    background-color: rgb(203, 203, 181);
  }
}

#jingdu {
  display: flex;
  justify-content: space-around;
  background-color: white;
  border-radius: 6px 6px 0 0;
  align-items: center;
  height: 10vh;
  width: 60vw;
  letter-spacing: 1px;
  color: rgb(136, 136, 137);

  .zhi {
    color: black;
    font-weight: bold;
  }
}</style>
